import { useState } from 'react';
import { createPortal } from 'react-dom';

export const useControlledState = <T>(state?: T, onChange?: (state?: T) => void): [T, (state?: T) => void] => {
  const [internalState, setInternalState] = useState<T>(state as T);
  const controlled = (values?: T) => {
    if (typeof onChange === 'function') onChange(values);
  };

  const uncontrolled = (values?: T) => {
    setInternalState(values as T);
    if (typeof onChange === 'function') onChange(values);
  };

  // 受控
  if (state !== undefined) {
    return [state, controlled];
  }
  // 非受控
  return [internalState, uncontrolled];
};

let _container!: HTMLDivElement;

export const usePortal = () => {
  if (!_container) {
    _container = document.createElement('div');
    _container.className = 'smap-portal-container';
    _container.style.position = 'absolute';
    _container.style.bottom = '10px';
    _container.style.left = '50%';
    _container.style.transform = 'translateX(-50%)';
    document.body.appendChild(_container);
  }
  return { container: _container, createPortal: (node: React.ReactNode) => createPortal(node, _container) };
};
